<template>
    <div id="music-content">
         <audio :loop="isLoop" 
         :src="musicIndex.url"
          autoplay
           @ended="musicEnd"
           @proggress="musicLoad"
           @loadstart="musicLoad"
           @play = "() =>{
               IndicatorInfo({close: true })
           }"
           ></audio>
         <div class="header">
                <mt-header title="车神音乐">
                        <mt-button icon="back" slot="left" @click="() => {
                            setState({homePage: 'home',tabBarShow: true,
                            seachInit: keyWord, musicCurrentTime: rangeValue}) 
                            this.audioDom.pause()                         
                            }">
                            返回
                        </mt-button>
                        <mt-button icon="more" slot="right" @click="() =>{
                        showMusicOpation = !showMusicOpation}">

                        </mt-button>
                    </mt-header>
            </div>
        <!-- 搜索按钮 -->
          <div class="music-seach-input">
            <input type="seach" v-model="keyWord" v-focus :placeholder="seachInit" 
            @keyup.enter="() => {
                readMore = false
                seachMusic()
            }"
            >
            <p class="music-seach-btn" @click="() =>{
                readMore = false
                seachMusic()
                }">搜索</p>
        </div>

        <!-- 歌曲列表 -->
        <transition
            name="word"
        >
             <div v-show="!isShow" id="music">
                <div class="content">
                    <div class="music-content">
                        <!-- 歌曲每一项 -->
                        <div class="music-item" v-for="(val ,index) in musicList" :key="index" @click="musicListen(index)">
                            <!-- 播放哪个就显示 哪个的海报 -->
                            <div class="music-pic">
                                <img :src="val.pic" :class="['music-pic-active', {musicPicRotate: mCurrentIndex === index}]">
                            </div>
                            <div class="music-info-item">
                                 <span class="music-name">{{val.name}}</span>
                                 <span class="music-singer">{{val.singer}}</span>
                            </div>
                        </div>

                        <div v-if="musicList.length === 0" class="music-no-msg">
                            {{musicMsg}} 
                        </div>
                        <div v-else class="music-more" @click="()=>{ 
                            musicPage++
                            readMore = true
                            seachMusic()}"
                        >
                            {{musicMore}}
                        </div>
                    </div>
                </div>
            </div>
        </transition>

        <!-- 播放 -->
        <transition
            name="play"
        >
            <div v-if="isShow" id="musicListen">
                <div class="music-content">
                    <div class="poster">
                        <img :src="musicIndex.pic" alt="">
                    </div>
                    <div class="opation">
                        <span class="iconfont icon-jiantou9-copy" @click="() => { isNextPre = false; musicNext()}"></span>
                        <!-- 打开按钮 -->
                        <span v-show="isPlay" class="iconfont icon-zanting-" @click="pauseMusic"></span>
                        <!-- 关闭按钮 -->
                        <span v-show="!isPlay" class="iconfont icon-yinpinbofang" @click="pauseMusic"></span>
                        <span class="iconfont icon-jiantou" @click="() => { isNextPre = true; musicNext()}"></span>
                    </div>
                    <div class="progess">
                        <mt-range
                            @input="rangeChange"
                            @change="rangrStop"
                            v-model="rangeValue"
                            :value="rangeValue"
                            :min="0"
                            :max="musicIndex.time"
                            :step="10"
                            :bar-height="15">
                        </mt-range>
                    </div>
                    <!-- 歌曲信息 -->
                    <div class="musicInfo">
                        <p>{{musicIndex.singer}}</p>
                        <p> {{ musicIndex.name}}</p>
                    </div>                
                </div>
            </div>
        </transition>

        <!-- 播放列表最小化 -->
        <transition
            name="musicSmall"
        >
            <div  class="musicListen-Info" @click="() =>{isShow = !isShow}">
                <img :src="musicIndex.pic">
                <div class="musicInfo">
                    <p> {{ musicIndex.name}}</p>
                    <p>{{musicIndex.singer}}</p>
                </div>
                 <div class="opation">
                    <!-- 打开按钮 -->
                    <span v-show="isPlay" class="iconfont icon-zanting-" @click.stop="pauseMusic"></span>
                    <!-- 关闭按钮 -->
                    <span v-show="!isPlay" class="iconfont icon-yinpinbofang" @click.stop="pauseMusic"></span>                  
                </div>
            </div>
        </transition>

        <!-- 模式弹窗 -->
         <div class="music-opation">
            <mt-actionsheet
                :actions="options"
                v-model="showMusicOpation"
                cancelText=""
            >
            </mt-actionsheet>
        </div>
    </div> 
</template>
<script>

import axios from 'axios'
import {mapMutations, mapState} from 'vuex'
import { MessageBox} from 'mint-ui'

export default {
    data(){
        return {
            keyWord: '',
            musicLimit: 10,//搜索最大条数
            musicData: [],
            musicMore: '点击加载更多...',
            readMore: false,//是否点击了加载更多
            musicPage: 0,
            getMusicTime: 1000,//搜索歌曲时间限度
            musicMsg: '暂无歌曲',

            //歌单和 播放列表来回切换
            isShow: false,
            //暂停和播放来回切换
            //false 显示关闭  true显示 打开
            isPlay: false,
            //audio DOM对象
            audioDom: {},
            //是否单曲循环
            isLoop: true,
            isNextPre: true, //默认下一首
            flagLimit: true,
            flaglimitTime: 1000,//限制时间长短

            //播放
            heaedrMsg: '车神音乐',
            showMusicOpation: false,
            options: [
                {name:'单曲循环', method: this.musicSelectList},
                {name:'顺序播放', method: this.musicSelectList},
                {name:'随机播放', method: this.musicSelectList},
                {name:'播放一次', method: this.musicSelectList}
                ],
                rangeValue: 0,
            mCurrentIndex: this.$store.state.musicCurrentIndex,//标志当前播放的索引值
            isLoad: true//首次进入是不需要加载的
        }
    },
    computed:{
        ...mapState([
            'musicList',//搜索歌曲列表
            'musicIndex',//当前播放歌曲信息
            'tabBarShow',//底部导航栏是否显示
            'seachInit',//默认搜索关键字
            'musicCurrentTime',//退出播放时间
            'musicMode',//音乐模式
            'musicCurrentIndex',//当前歌曲索引
            'musicMaxLen'//歌曲的最大长度
        ])
    },

    //在这里进行 一些页面的操作
    methods:{
        ...mapMutations([
            'setState',
            'IndicatorInfo',
            'toastInfo'
        ]),
        
        //搜索音乐
        seachMusic(){
            
            //搜索歌曲应该立马显示 歌曲列表  不是取反 直接设置 
            this.isShow = false

            //关键字 不存在  设置 默认值
            if(!this.keyWord) this.keyWord = this.seachInit

            // 发请求 拿取数据列表
             this.getmusic()
                .then( async (res) =>{
                //获取歌曲列表
                this.musicData = await res.data.data

                //不是点击加载更多 音乐数组 不是拼接
                if(!this.readMore){
                    this.setState({musicList: this.musicData})
                    //设置歌曲的最大长度
                    this.setMusicMaxLen()
                }else{
                    //点击加载更多拼接
                    this.setState({musicList: this.musicList.concat(this.musicData)})
                    //设置歌曲的最大长度
                    this.setMusicMaxLen()
                }


                //第一次找不到歌曲 一旦即在过一次 就不会在执行
                if(this.musicList.length === 0){
                    this.IndicatorInfo({close: true})
                    //歌曲不存在 把加载框去掉
                    this.musicMsg = '搜索歌曲不存在'
                    return   
                }

                //一旦获取的条数 小于最小条数 则为没有加载更多了  因为这里没有获取到做大的数目，
                //因此可能等于10的时候，刚刚好也没有更多了，就认栽吧
                if(this.musicData.length < this.musicLimit){
                    this.musicMore = '没有更多了'
                }

                //搜索到歌曲立马关闭提示框
                await this.IndicatorInfo({close: true})

                this.musicData = []

            }, () =>{
                this.IndicatorInfo({close: true})
                alert('获取歌曲失败稍后再试')
            })            
        },

        //前往某个歌曲听歌
        musicListen(index){
            //显示播放按钮
            this.isShow = !this.isShow
            // 这里如果 点击当前歌曲和上一次的歌曲一样，那么就不会在继续往下执行  
            //而是前往判断 音乐的暂停和播放   否则 这里只是设置点击歌曲为当前播放歌曲
            if(this.musicCurrentIndex === index) return this.pauseMusic()

            //设置 歌曲的最大值  和当前歌曲索引
            this.setState({musicIndex: this.musicList[index], musicCurrentIndex: index})
            //同步当前歌曲 索引
            this.mCurrentIndex = index

            //显示打开按钮 true  这里必须直接这只为 true
            this.isPlay = true

        },

        //暂停音乐
        pauseMusic(){
            /*
                暂停 说明 要打开按钮 true
            */

           //此时这条语句 只有返回 到首页 在进去音乐，首次点击暂停播放按钮才会执行
           //不是首次点击播放暂停 不会执行  只有this.musicCurrentTime === this.rangeValue才是最合适的
           if(this.musicCurrentTime === this.rangeValue){
               this.audioDom.currentTime = this.musicCurrentTime
           }

            if(this.audioDom.paused){
                this.audioDom.play()
            }else{
                this.audioDom.pause()          
            }
            this.isPlay = !this.isPlay
        },

        //进度条range的变化
        rangeChange(){
            //暂停音乐
            this.audioDom.pause()
            this.audioDom.currentTime = this.rangeValue
        },

        //一旦点击抬起 就播放音乐
        rangrStop(){
            
            //此时如果是暂停状态， 拖动滚动条，松开不会播放
            if(!this.isPlay){
                return
            }
            this.audioDom.play()        
        },

        //发请求拿取数据
        getmusic(){

            this.IndicatorInfo({msg: '正在加载歌曲...'})
            const url = `https://api.itooi.cn/music/kugou/search?key=579621905&s=${this.keyWord}&limit=${this.musicLimit}&offset=${this.musicPage}&type=song`
                            // 现在就是解决 加载时间过长问题
            return axios({
                method: 'post',
                url
            })
        },

        //播放
        //选择列表 单曲循环 还是只播放一次 循环播放
        musicSelectList(ev){

            this.setState({musicMode: ev.name})

            //单曲循环直接设置为 true  其他都是false
            if(this.musicMode === '单曲循环') return this.isLoop = true 
              
            this.isLoop = false
        },
    
        //如果不是 单曲循环都会触发
        musicEnd(){
           
            switch(this.musicMode){
                case '顺序播放':
                 
                    this.mCurrentIndex++
                    this.setState({
                        musicCurrentIndex: this.mCurrentIndex,
                         musicIndex: this.musicList[this.mCurrentIndex]
                         })    
                    break
                case '随机播放':
                   this.getRandomIndex() 
                    break
                default: 
                    return
            }
        },

        //获取随机数
        getRandomIndex(){
            
            this.mCurrentIndex = Math.floor(Math.random()*this.musicMaxLen)
            this.setState({
                musicCurrentIndex: this.mCurrentIndex,
                musicIndex: this.musicList[this.mCurrentIndex]
            })  
        },

        //随机歌曲不可播放
        getReanNo(){
            
             let newIndex = Math.floor(Math.random()*this.musicMaxLen)

            /*
                目的：
                    防止当前 的随机歌曲为又是当前歌曲
                    因此如果当前随机数 等于 当前歌曲的索引 就统一 + 1 否则就等于该随机数
                    但是只有 最后一条歌曲不能 + 1 因为不能加了
                    判断顺序不能换
            */

            if(this.mCurrentIndex === this.musicMaxLen - 1 && newIndex ===  this.mCurrentIndex){               
               this.mCurrentIndex = newIndex -1              
            }else if(newIndex ===  this.mCurrentIndex){      
               this.mCurrentIndex = newIndex + 1
            }else{
               this.mCurrentIndex = newIndex
            }
            

            this.setState({
                musicCurrentIndex: this.mCurrentIndex,
                musicIndex: this.musicList[this.mCurrentIndex]
            })
                
        },

        //下一首或者上上一首
        musicNext(){

            /*
                isNextPre true  下一首
                            false 上一首
            */

           //播放按钮打开
           this.isPlay = true//直接设置true


            if(this.flagLimit) {

                this.flagLimit = !this.flagLimit

                if(this.isNextPre){
                    if(this.mCurrentIndex === this.musicMaxLen - 1){
                        this.mCurrentIndex = 0
                    }else{
                        this.mCurrentIndex = this.mCurrentIndex + 1
                    }
                }else{
                    if(this.mCurrentIndex === 0){
                        this.mCurrentIndex = this.musicMaxLen - 1
                    }else{
                        this.mCurrentIndex = this.mCurrentIndex - 1
                    }
                }
            
                this.setState({
                    musicCurrentIndex: this.mCurrentIndex,
                    musicIndex: this.musicList[this.mCurrentIndex]
                })

                setTimeout(() =>{
                    this.flagLimit = !this.flagLimit
                }, this.flaglimitTime)
            }
        },

        //音乐加载过程
        musicLoad(){
            if(this.isLoad) return
            if(this.audioDom.readyState > 1) {
                return this.IndicatorInfo({close: true })
            }else{
                this.IndicatorInfo({msg: '正在加载音乐'})
            }
        },

        //设置歌曲的的最大长度
        setMusicMaxLen(){
            this.setState({musicMaxLen: this.musicList.length})
        }       
    },

    created(){
         //拿取上一次歌曲播放时间
        this.rangeValue = this.musicCurrentTime
        this.setState({musicMaxLen: this.musicList.length})
    },

    mounted(){
        
        const opationImgNode = document.querySelectorAll('.opation > img')
        this.audioDom = document.querySelector('audio')
        //隐藏底部导航条
        this.setState({tabBarShow: false})

        setTimeout(() =>{
            this.isLoad = false
        },100)
        
        //一进来音乐都是关闭的
        this.audioDom.pause()
        
        //这里设置按钮的高度 与宽度一样
        for(let item of opationImgNode){
            item.style.height = item.offsetWidth + 'px'
        }
        
        //这里写播放器的逻辑
        this.audioDom.oncanplay = () =>{
        }

        //时间 同步进度条
        this.audioDom.ontimeupdate = () =>{
            //设置 range进度条的值 
            this.rangeValue = Math.round(this.audioDom.currentTime)
        }

        this.audioDom.onerror = () =>{
            MessageBox({
                title: '提示',
                message: '当前歌曲不可播放，将随机播放一首'
            }).then(action =>{

               this.IndicatorInfo({close: true })
               this.getReanNo()
            })
        }
    },
    //过滤器
    filters:{
        musicNameFilter(musicName){
            const reg = new RegExp(/】$/)
            if(reg.test(musicName)){
                return musicName.split('【')[0]
            }
        }
    },
    //自定义指令
    directives:{
        //文本获取焦点
        focus: {
            inserted: function (el) {
                el.focus()
            },
        }
    }
}
</script>
<style lang="less" scoped>
    @url: 'http://img0.imgtn.bdimg.com/it/u=1334403820,3094317072&fm=26&gp=0.jpg';
    #music-content{
        top:0;
        bottom:0;
        position:fixed;
        overflow-y:scroll;
        overflow-x:hidden;
        width: 100%;
        height: 100%;
        background: url(@url) no-repeat;
        background-size: 100% 100%;
        //搜索框
        .music-seach-input{
            position: fixed;
            top: 40px;
            padding: 5px 10px 0;
            width: 100%;
            height: 30px;
            margin-bottom: 15px;
            box-sizing: border-box;
            display: flex;
            z-index: 10;
            > input{
                flex: 4;
                height: 100%;
                text-indent: 20px;
                opacity: 0.7;
                // background-color: #9DDBE2;
            }
            > .music-seach-btn{
                flex: 2;
                height: 30px;
                text-align: center;
                line-height: 30px;
                margin: 0;
                background: #2BA2FA;
                color: #fff;
                opacity: 0.7;
            }
        }
            
        //歌曲列表
        #music{
            margin-top: 80px;
            padding-bottom: 60px;
            .content{
                height: 100%;
                .music-content{
                    height: 100%;
                    .music-item:first-child{
                        border-top: 1px solid #E5E5E5;
                    }
                    .music-item:last-child{
                        border-bottom: none;
                    }
                    .music-item{  
                        display: flex;
                        padding: 5px 10px;
                        border-bottom: 1px solid #E5E5E5;
                        .music-pic{
                            margin-right: 10px;
                            .music-pic-active{
                               height: 50px;
                               width: 50px;
                               border-radius: 50%;
                            }
                            .musicPicRotate{
                               height: 60px;
                               width: 60px;
                               animation: posterImgRotate 30s linear 0.2s infinite;
                            }
                        }

                        .music-info-item{
                            display: flex;
                            flex: 1;
                            flex-direction: column;
                            .music-name{
                                font-size: 14px;
                                color: #2a2a2a;
                            }
                            .music-singer{
                                text-align: right;
                                margin-right: 25px;
                                font-size: 13px;
                                color: #000000;
                                margin-top: 5px;
                            }
                        }
                    }
                    //加载更多
                    .music-more{
                        height: 30px;
                        text-align: center;
                        line-height: 30px;
                        background: #A1C1E6;
                    }

                    .music-no-msg{
                        height: 100px;
                        line-height: 100px;
                        text-align: center;
                        font-size: 25px;
                        color: #ccc;
                    }
                }
            }

        }

        // 播放
        #musicListen{
            position: fixed;
            top: 80px;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: -1;
            .music-content{
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                .music-opation{
                    position: absolute;
                    z-index: 1;
                }
                    .poster{
                        position: relative;
                        flex: 4;
                        margin: 50px 0 30px;           
                        > img{
                            position: absolute;
                            top: 0;
                            left: 0;
                            right: 0;
                            bottom: 0;
                            margin: auto;
                            width: 60%;
                            border-radius: 50%;
                            animation: posterImgRotate 30s linear 0.2s infinite;
                        }
                    }
                    .opation{
                    flex: 2;
                    display: flex;
                    justify-content: space-around;
                    > span{
                        //    padding-top: 30px;
                        font-size: 50px;
                        color: #B0B0B1;
                    }
                    }
                    .progess{
                        flex: 1;
                    }
                    .musicInfo{
                        flex: 5;
                        text-align: center;
                        font-size: 16px;
                        color: #F9CC9D;
                    }
            }
        }

        //播放列表缩小化
        .musicListen-Info{
            position: fixed;
            width: 100%;
            height: 50px;
            padding: 5px;
            background: #342948;
            bottom: 0;
            left: 0;
            display: flex;
            > img{
                flex: 2;
                width: 50px;
                border-radius: 50%;
                animation: posterImgRotate 30s linear 0.2s infinite;
            }
            > .musicInfo{
                flex: 9;
                display: flex;
                flex-direction: column;
                padding: 0 15px;
                > p{
                    flex: 1;
                    margin: 0;
                    font-size: 12px;
                    color: #ccc;
                }
                P:last-child{
                    text-align: right;
                }
            }
            > .opation{
                flex: 2;
                margin-right: 20px;
                display: flex;
                justify-content: space-around;
                line-height: 50px;
                > span{
                    font-size: 40px;
                    color: #736450;
                }
            }
        }

    }


    //播放列表动画
    .play-enter,
    .play-leave-to{
        transform: translate3d(100%, -100%, 0);
    }
    .play-enter-active,
    .play-leave-active{
        transition: 0.5s;
    }

    //歌词的
    .word-enter,
    .word-leave-to{
       opacity: 0;
    }
    .word-enter-active,
    .word-leave-active{
        transition: 0.6s;
    }

    //这是播放列表缩小化的
    .musicSmall-enter,
    .musicSmall-leave-to{
      transform: translateY(100%);
    }
    .musicSmall-enter-active,
    .musicSmall-leave-active{
        transition: 0.5s 0.5s;
    }

    @keyframes posterImgRotate{
        0%{
            transform: rotate(0deg);
        }
        100%{
            transform: rotate(360deg);
        }
	}
</style>
